<?php
/**
 * Created by PhpStorm
 * User: 王帆
 * Date: 2020-07-13
 * Time: 10:58
 */
require('../phpMQTT.php');
$data = require('config.php');
$param_arr = getopt('t:i:');
if (!key_exists('t',$param_arr)){
    echo "缺少参数!\n";die();
}
$t = $param_arr['t'];
$i = $param_arr['i']; // 确保clientId唯一

if (key_exists($t,$data['topicArray'])){
    $mqtt = new Bluerhinos\phpMQTT($data['config']['server'], $data['config']['port'], $data['config']['subscriber_client_id'].$i);
    if (!$mqtt->connect(true, NULL, $data['config']['username'], $data['config']['password'])) {
        exit(1);
    }
}else {
    echo "专题不存在!\n";die();
}

$mqtt->debug = true;

$topic = $data['topicArray'][$t];


$topics[$topic['key']] = array('qos' => 0, 'function' => 'procMsg');
//$topics['bluerhinos/phpMQTT/examples/publishtest1'] = array('qos' => 0, 'function' => 'procMsg');

//var_dump($topic['key']);die;
$mqtt->subscribe($topics, 0);
while($mqtt->proc()) {

}
$mqtt->close();
function procMsg($topic, $msg){
    $msgArr = json_decode($msg,true);
    echo 'Msg Recieved : ' . date('Y-m-d H:i:s') . "\n";
    echo "Topic: {$topic}\n";
    echo "时间：".$msgArr['time']."\n";
    echo "单据类型：".$msgArr['name']."\n";
    echo "ID：".$msgArr['k']."\n";
}
//{"time":"2021-12-08 15:23:59","name":"\u62a5\u635f\u5355","k":"123"}